//
//  MeHeaderView.swift
//  whale
//
//  Created by topnet on 2022/7/6.
//

import UIKit
import StoreKit
class MeHeaderView: ICBaseView {

    fileprivate var packageModel: PackageModel! = .init()
    fileprivate var iapModel: IAPModel! = .init()
    
    func updateData() {
        infoV.updateData()
    }
    
    override func _initUI() {
        infoV = MeInfoView()
        
        favorV = FavorView()
    
        da.addSubviews(sub: [infoV, favorV])
        frame.size.width = UIScreen.width
        initFrame()
    }
    
    override func _initData() {
        favorV.configTop(top: ["$4.99/月度", "$47.99/年度"])
        favorV.configDown(down: ["购买", "购买"])
        setupItem()
        favorV.didSelect = { [weak self] index in
            let userDefault = UserDefaults.standard
            userDefault.set(index + 1, forKey: "selected")
            self?.da.vc?.tabBarController?.selectedIndex = 1
        }
    }
    
    func setupItem() {
        if StoreKit.shared.isActivePaidSubscription() {
            
        }else {
            self.packageModel = .init()
            self.packageModel.packages.subscribe { (packages) in
                self.iapModel = .init()
                self.iapModel.skProducts.subscribe { (skProducts) in
                    self.setupData(skProducts)
                } onCompleted: {
                    
                }.disposed(by: self.dispose)
                self.iapModel.retrive(products: packages.map { $0.packageId })
                
            } onCompleted: {
                
            }.disposed(by: self.dispose)
            self.packageModel.getPackages()
             
        }
    }
    
    private func setupData(_ skProductSorted: [SKProduct]) {
        
        // MONTHLY
        let skProduct1 = skProductSorted.first(where: { $0.productIdentifier.contains("mo") })
        
        // YEARLY
        let skProduct2 = skProductSorted.first(where: { $0.productIdentifier.contains("ye") })
        
        
        favorV.configTop(top: [(skProduct1?.priceStringForProduct() ?? "$4.99") + "/月度", (skProduct2?.priceStringForProduct() ?? "$47.99") + "/年度"])
       
    }
    
    override func initFrame() {
        infoV.width(bounds.width)
        super.initFrame()
        favorV.left_right(self, x: 12.adapter).top(infoV.frame.maxY).height(46.adapter)
        
        autoBottomInset = 20.adapter
        lastV = favorV
        autoHeight()
    }

    private var infoV: MeInfoView!
    private var favorV: FavorView!
    
    private lazy var dispose = DisposeBag()
}
